package com.samphanie.dries.security.jwt;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.samphanie.dries.properties.AppProperties;
import com.samphanie.dries.util.OptionalEx;
import io.jsonwebtoken.*;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author ZSY
 * @createTime 2021/3/2 19:10
 */
@RequiredArgsConstructor
@Component
public class JwtFilter extends OncePerRequestFilter {

    private final AppProperties appProperties;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (checkJwtToken(request)) {
//            validateToken(request)
////                    .filter(claims -> claims.get("authorities") != null) // 判断是否有值
//                    // ifPresentOrelse(this::setUpSpringAuthentication)
//                    .map(claims -> {
//                        if (claims.get("authorities") != null) {
//                            this.setUpSpringAuthentication(claims);
//                        }  else {
//                            SecurityContextHolder.clearContext();
//                        }
//
//                        return claims;
//                    })
//                    ;

             OptionalEx.ifPresent(validateToken(request), this::setUpSpringAuthentication).orElse(SecurityContextHolder::clearContext);

        }

        filterChain.doFilter(request, response);
    }

    private void setUpSpringAuthentication(Claims claims) {
        List<?> rawList = Convert.toList(claims.get("authorities"));
        List<SimpleGrantedAuthority> authorities = rawList.stream()
                .map(String::valueOf)
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());

        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(claims.getSubject(), null, authorities);
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    private Optional<Claims> validateToken(HttpServletRequest request) {
        String jwtToken = request.getHeader(appProperties.getJwt().getHeader()
                .replace(appProperties.getJwt().getPrefix(), ""));

        try {
            return Optional.of(Jwts.parserBuilder().setSigningKey(appProperties.getJwt().getKey()).build().parseClaimsJws(jwtToken).getBody());
        } catch (ExpiredJwtException | SecurityException | MalformedJwtException | UnsupportedJwtException | IllegalArgumentException e) {
            return Optional.empty();
        }

    }

    /**
     * 检查 JWT Token 是否在 HTTP 请求头中
     *
     * @param request HTTP 请求
     * @return
     */
    private boolean checkJwtToken(HttpServletRequest request) {

        String authHeader = request.getHeader(appProperties.getJwt().getHeader());
        return authHeader != null && authHeader.startsWith(appProperties.getJwt().getPrefix());
    }
}
